<template>
    <h2>城市销售量</h2>
    <div ref="chart" class="cmap"></div>
</template>

<script setup>
import { ref, inject, onMounted } from 'vue'
import { useDebouncedResize } from '@/utils/hooks/useDebouncedResize'
import { useEChart } from '@/utils/hooks/useEchart'

const axios = inject('axios')
// 引入全局echarts
const echarts = inject('echarts')
// 获取图表的dom
const chart = ref(null)
const cmapData = ref(null)

// 使用抽离的echarts Hook
const { initChart, disposeChart, getInstance, resizeChart } = useEChart()

const getCmapData = async () => {
    const res = await axios.get('/cmap/data')
    cmapData.value = res.data.data
}
onMounted(async () => {
    await getCmapData()
    echarts.registerMap('cmap', cmapData.value)
    const option = {
        geo: {
            map: 'cmap',
            itemStyle: {
                areaColor: '#0099ff',
                borderColor: '#00ffff',
                shadowColor: 'rgba(230, 130, 70, 0.5)',
                shadowBlur: 30,
                emphasis: {
                    focus: 'self', // none
                },
            },
        },
        tooltip: {
            trigger: 'item',
        },
        series: [
            {
                type: 'scatter',
                name: '所在城市销售额',
                itemStyle: {
                    color: 'red',
                },
                coordinateSystem: 'geo',
                data: [
                    { name: '北京', value: [116.46, 39.92, 4367] },
                    { name: '上海', value: [121.48, 31.22, 8675] },
                    { name: '广州', value: [113.28, 23.12, 187] },
                    { name: '深圳', value: [114.07, 22.62, 2461] },
                    { name: '成都', value: [104.06, 30.67, 4367] },
                ],
            },
        ],
        // 设置视觉映射组件
        visualMap: {
            type: 'continuous',
            min: 100,
            max: 5000, // 根据你的数据最大值调整
            calculable: true,
            inRange: {
                color: ['#50a3ba', '#eac736', '#d94e5d'],
            },
            textStyle: {
                color: '#fff',
            },
            // 关键定位配置 - 让映射显示在容器内并贴近左下角
            left: '0%', // 距离容器左侧5%
            bottom: '5%', // 距离容器底部15%
            orient: 'vertical', // 垂直显示
            itemWidth: 18, // 图例宽度
            itemHeight: 130, // 图例高度
            textGap: 8, // 文字与图例的间距
        },
    }
    initChart(echarts, chart, option)
})
// 使用抽离的防抖resize Hook
useDebouncedResize(resizeChart, 500)
</script>

<style lang="less" scoped>
h2 {
    /* 48像素 */
    height: 0.6rem;
    color: #fff;
    line-height: 0.6rem;
    text-align: center;
    font-size: 0.25rem;
}
.cmap {
    width: 100%;
    height: 100%;
}
</style>
